import { useMemberStore } from '@/stores'

const baseURl = 'https://pcapi-xiaotuxian-front-devtest.itheima.net'

const httpInterceptor = {
  //拦截前触发
  invoke(options: UniApp.RequestOptions) {
    //1.非http开头的请求，需要拼接
    if (!options.url.startsWith('http')) {
      options.url = baseURl + options.url
    }
    options.header = {
      ...options.header,
      'source-client': 'miniapp',
    }
    //2.请求时间
    options.timeout = 20000
    const memberStore = useMemberStore()
    const token = memberStore.profile?.token
    if (token) {
      options.header.Authorization = token
    }
    // console.log('请求拦截器', options)
  },
}
uni.addInterceptor('request', httpInterceptor)
uni.addInterceptor('unloadFile', httpInterceptor)
/**
 *
 * @param UniApp.RequestOptions
 * @returns Promise
 * 1.返回Promise对象
 * 2.请求成功后
 *   2.1.resolve(res.data)
 *   2.2.添加类型，支持泛型
 * 3.请求失败后
 *   3.1 网络错误->提示用户换网络
 *   3.2 401错误->清理用户信息，跳转登录页面
 *   3.3 其他错误->提示后端错误信息轻提示
 *
 */
export type ResponseData<T> = {
  result: T
  code: string
  message: string
}
export const http = <T>(options: UniApp.RequestOptions) => {
  return new Promise<ResponseData<T>>((resolve, reject) => {
    uni.request({
      ...options,
      //请求成功
      success: (res) => {
        if (res.statusCode >= 200 && res.statusCode < 300) {
          resolve(res.data as ResponseData<T>)
        } else if (res.statusCode === 401) {
          // 401 错误，清理用户信息，跳转登录页面
          const memberStore = useMemberStore()
          memberStore.clearProfile()
          uni.navigateTo({
            url: '/pages/login/login',
          })
          reject(res)
        } else {
          //其他错误->提示后端错误信息轻提示
          uni.showToast({
            icon: 'none',
            title: (res.data as ResponseData<T>).message || '请求失败，请稍后再试',
            duration: 2000,
          })
          reject(res)
        }
      },
      //响应错误
      fail: (err) => {
        uni.showToast({
          icon: 'none',
          title: '网络错误，请稍后再试',
        })
        console.log('失败')
        reject(err)
      },
    })
  })
}
